﻿using HCQ2_Common.Constant;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;

namespace HCQ2WebAPI_Logic.Filters
{
    /// <summary>
    /// 统一模型验证
    /// </summary>
    public class ModelValidAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 在调用操作方法之前发生。
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ModelStateDictionary modelState = actionContext.ModelState;

            if (!modelState.IsValid)
            {
                //验证不通过
                List<string> messList = new List<string>();
                foreach (var key in modelState.Keys)
                {
                    var modelstate = modelState[key];
                    if (modelstate.Errors.Any())
                    {
                        messList.Add(modelstate.Errors.First().ErrorMessage);
                    }
                }
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK,
                                new HCQ2_Model.ViewModel.WebAPI.WebApiResultJsonModel()
                                {
                                    errcode = WebResultCode.Exception,
                                    errmsg = GlobalConstant.参数异常.ToString(),
                                    value = messList
                                });
            }
        }
    }
}
